package com.sky.controller.user;

import com.sky.constant.RedisDataBaseNameConstant;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "菜品接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(@ApiParam("分类id")Long categoryId) {
        log.info("根据分类id查询菜品:{}",categoryId);
        //查看redis缓存是否有
        List<DishVO> redisList = (List<DishVO>) redisTemplate.opsForValue().get(RedisDataBaseNameConstant.DISH_KEY + categoryId);
        log.info("根据分类id查询菜品,从redis缓存中查询:{}",redisList);
        if(redisList != null){
            //刷新缓存过期时间为10秒
            redisTemplate.expire(RedisDataBaseNameConstant.DISH_KEY + categoryId,RedisDataBaseNameConstant.RedisTimeout, TimeUnit.SECONDS);
            //若有，直接返回
            return Result.success(redisList);
        }else {
            //若没有，查询数据库 再存入缓存
            log.info("redis中没有分类菜品数据从mysql中查询!!");
            Dish dish = new Dish();
            dish.setCategoryId(categoryId);
            dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品
            List<DishVO> list = dishService.listWithFlavor(dish);
            //将查询结果存入redis缓存,设置过期时间为20秒
            redisTemplate.opsForValue().set(RedisDataBaseNameConstant.DISH_KEY + categoryId,list,RedisDataBaseNameConstant.RedisTimeout, TimeUnit.SECONDS);
            return Result.success(list);
        }
    }

}
